import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/foundation.dart';

// 封装错误分类和处理逻辑
class AudioErrorHandler {
  static bool isMediaCodecError(dynamic error) {
    final errorStr = error.toString().toLowerCase();
    return errorStr.contains('mediacodec') ||
        errorStr.contains('codec') ||
        errorStr.contains('unexpected runtime error') ||
        errorStr.contains('platform exception');
  }

  static bool isNetworkError(dynamic error) {
    final errorStr = error.toString().toLowerCase();
    return errorStr.contains('network') ||
        errorStr.contains('connection') ||
        errorStr.contains('timeout') ||
        errorStr.contains('socketexception');
  }

  static bool isBufferingError(dynamic error) {
    final errorStr = error.toString().toLowerCase();
    return errorStr.contains('buffer') ||
        errorStr.contains('stuck buffering') ||
        errorStr.contains('type_unexpected');
  }

  static bool isStuckBufferingError(dynamic error) {
    final errorStr = error.toString().toLowerCase();
    return errorStr.contains('stuck buffering') ||
        errorStr.contains('playback stuck buffering');
  }

  // 获取友好的错误消息
  static String getFriendlyErrorMessage(
    dynamic error, {
    bool isAndroid = false,
  }) {
    if (isMediaCodecError(error)) {
      return isAndroid ? '安卓解码器错误，正在尝试修复...' : '解码器错误，正在尝试恢复...';
    } else if (isNetworkError(error)) {
      return '网络连接问题，请检查网络后重试';
    } else if (isStuckBufferingError(error)) {
      return '播放缓冲卡住，正在重置播放器...';
    } else if (isBufferingError(error)) {
      return '缓冲卡住，正在尝试恢复播放...';
    } else {
      return '播放出错: $error';
    }
  }
}

/// 音频播放器状态
class AudioPlayerState {
  final Duration position;
  final Duration bufferedPosition;
  final Duration duration;
  final bool isPlaying;
  final bool isLoading;
  final bool isBuffering;
  final String? error;
  final List<BufferedRange> bufferedRanges;
  final double loadingProgress;
  final String? currentUrl; // 添加当前URL信息，用于区分不同音频

  const AudioPlayerState({
    this.position = Duration.zero,
    this.bufferedPosition = Duration.zero,
    this.duration = Duration.zero,
    this.isPlaying = false,
    this.isLoading = true,
    this.isBuffering = false,
    this.error,
    this.bufferedRanges = const [],
    this.loadingProgress = 0.0,
    this.currentUrl,
  });

  /// 创建一个新的状态实例
  AudioPlayerState copyWith({
    Duration? position,
    Duration? bufferedPosition,
    Duration? duration,
    bool? isPlaying,
    bool? isLoading,
    bool? isBuffering,
    String? error,
    List<BufferedRange>? bufferedRanges,
    double? loadingProgress,
    String? currentUrl,
  }) {
    return AudioPlayerState(
      position: position ?? this.position,
      bufferedPosition: bufferedPosition ?? this.bufferedPosition,
      duration: duration ?? this.duration,
      isPlaying: isPlaying ?? this.isPlaying,
      isLoading: isLoading ?? this.isLoading,
      isBuffering: isBuffering ?? this.isBuffering,
      error: error,
      bufferedRanges: bufferedRanges ?? this.bufferedRanges,
      loadingProgress: loadingProgress ?? this.loadingProgress,
      currentUrl: currentUrl ?? this.currentUrl,
    );
  }

  /// 清除错误
  AudioPlayerState clearError() {
    return copyWith(error: null);
  }

  /// 检查指定位置是否已缓冲
  bool isPositionBuffered(Duration position) {
    // 如果位置为0，总是认为已缓冲
    if (position.inMilliseconds <= 0) {
      return true;
    }

    // 如果已经播放到接近结尾，认为整个文件已缓冲
    if (this.position.inMilliseconds > 0 &&
        duration.inMilliseconds > 0 &&
        (duration - this.position).inMilliseconds < 10000) {
      return true;
    }

    // 如果加载进度超过95%，认为整个文件已缓冲
    if (loadingProgress > 0.95) {
      return true;
    }

    // 如果没有缓冲区间信息但有bufferedPosition，基于bufferedPosition判断
    if (bufferedRanges.isEmpty && bufferedPosition.inMilliseconds > 0) {
      // 更宽松的判断：如果目标位置小于缓冲位置的95%，认为已缓冲
      // 这有助于避免边界情况下的重新缓冲
      return position.inMilliseconds <=
          (bufferedPosition.inMilliseconds * 0.95);
    }

    // 遍历所有缓冲区间检查
    for (var range in bufferedRanges) {
      // 更宽松的区间判断：如果位置接近区间边界也视为已缓冲
      final safetyMargin = Duration(milliseconds: 500);
      if (position >= range.start - safetyMargin &&
          position <= range.end + safetyMargin) {
        return true;
      }
    }

    // 安全检查：如果播放位置接近缓冲位置，也视为已缓冲
    // 增加安全边界到2秒，特别是对于FLAC等高质量音频
    if (bufferedPosition.inMilliseconds > 0 &&
        (bufferedPosition - position).inMilliseconds < 2000 &&
        (bufferedPosition - position).inMilliseconds >= 0) {
      return true;
    }

    // 如果当前位置和目标位置都在文件的前20%范围内，认为已缓冲
    // 这是因为前面部分通常会被优先缓冲
    if (duration.inMilliseconds > 0) {
      final fileStartRegion = duration.inMilliseconds * 0.2;
      if (position.inMilliseconds < fileStartRegion &&
          this.position.inMilliseconds < fileStartRegion) {
        return true;
      }
    }

    return false;
  }

  /// 获取最近的已缓冲位置（用于智能跳转）
  Duration getNearestBufferedPosition(Duration position) {
    if (bufferedRanges.isEmpty) {
      return Duration.zero;
    }

    // 如果请求位置已缓冲，直接返回
    if (isPositionBuffered(position)) {
      return position;
    }

    // 找出所有缓冲区间中最近的点
    Duration bestPosition = Duration.zero;
    Duration minDistance = const Duration(days: 1); // 初始设一个很大的值

    for (var range in bufferedRanges) {
      // 检查区间起点距离
      final distanceToStart = (range.start - position).abs();
      if (distanceToStart < minDistance) {
        minDistance = distanceToStart;
        bestPosition = range.start;
      }

      // 检查区间终点距离
      final distanceToEnd = (range.end - position).abs();
      if (distanceToEnd < minDistance) {
        minDistance = distanceToEnd;
        bestPosition = range.end;
      }
    }

    // 优先选择最大的已缓冲区间
    BufferedRange largestRange = bufferedRanges.first;
    for (var range in bufferedRanges) {
      if (range.end.inMilliseconds - range.start.inMilliseconds >
          largestRange.end.inMilliseconds - largestRange.start.inMilliseconds) {
        largestRange = range;
      }
    }

    // 如果最大缓冲区间和最近点的差距不大，优先使用最大区间的中点
    Duration largestRangeMiddle = Duration(
      milliseconds:
          (largestRange.start.inMilliseconds +
              largestRange.end.inMilliseconds) ~/
          2,
    );

    if ((largestRangeMiddle - bestPosition).abs() <
        const Duration(seconds: 5)) {
      return largestRangeMiddle;
    }

    return bestPosition;
  }

  /// 检查是否有错误
  bool get hasError => error != null;
}

/// 缓冲区间类
class BufferedRange {
  final Duration start;
  final Duration end;

  const BufferedRange(this.start, this.end);

  @override
  String toString() => 'BufferedRange($start - $end)';
}

/// 音频播放器控制器
class EnhancedAudioPlayer {
  final AudioPlayer _player = AudioPlayer();
  String? _currentUrl;
  Map<String, String>? _currentHeaders;
  final _stateController = StreamController<AudioPlayerState>.broadcast();
  Timer? _positionRefreshTimer;
  Timer? _recoveryTimer;
  bool _needReloadUrl = false;
  bool _disposed = false;
  bool _failedToLoad = false;
  Duration? _seekTarget;
  final List<BufferedRange> _bufferedRanges = [];
  bool _isSmartSeekEnabled = true;
  int _maxRetryCount = 3;
  int _retryCount = 0;
  double _loadingProgress = 0.0;
  int _bufferSize = 65536; // 增加默认缓冲区大小
  bool _hasTooManyErrors = false; // 追踪是否有太多错误
  DateTime? _lastErrorTime; // 记录最后一次错误时间
  int _consecutiveErrorCount = 0; // 连续错误计数

  /// 当前状态
  AudioPlayerState _currentState = const AudioPlayerState();

  /// 状态流
  Stream<AudioPlayerState> get stateStream => _stateController.stream;

  /// 初始化
  EnhancedAudioPlayer() {
    _initializeListeners();

    // 添加全局错误处理
    PlatformDispatcher.instance.onError = (error, stack) {
      if (!_disposed && error.toString().contains('MediaCodec')) {
        print('捕获到平台MediaCodec错误，正在尝试修复: $error');
        _handleGlobalMediaCodecError();
        return true; // 表示错误已处理
      }
      return false; // 让其他错误处理器处理
    };
  }

  /// 处理全局MediaCodec错误
  void _handleGlobalMediaCodecError() {
    // 防止在短时间内多次处理相同错误
    final now = DateTime.now();
    if (_lastErrorTime != null &&
        now.difference(_lastErrorTime!).inSeconds < 2) {
      _consecutiveErrorCount++;

      // 如果短时间内出现太多错误，标记播放器为严重错误状态
      if (_consecutiveErrorCount > 5) {
        _hasTooManyErrors = true;
        _updateState(error: '播放器出现严重错误，请重新加载页面');
        return;
      }
    } else {
      _consecutiveErrorCount = 1;
    }

    _lastErrorTime = now;

    // 尝试恢复播放
    if (_currentUrl != null && !_hasTooManyErrors) {
      _updateState(error: 'MediaCodec错误，正在尝试恢复...');
      _tryRecoverAndroidMediaCodec();
    }
  }

  /// 初始化监听器
  void _initializeListeners() {
    Timer? debounceTimer;
    const debounceDuration = Duration(milliseconds: 200); // 降低防抖时间以提高响应性

    _player.positionStream.listen((position) {
      debounceTimer?.cancel();
      debounceTimer = Timer(debounceDuration, () {
        if (!_disposed) _updateState(position: position);
      });
    });

    _player.bufferedPositionStream.listen((bufferedPosition) {
      // 对缓冲位置更新仍然快速响应，但增加一点延迟防止过于频繁更新
      Future.delayed(const Duration(milliseconds: 100), () {
        if (!_disposed) {
          _updateState(bufferedPosition: bufferedPosition);
          // 每次缓冲位置变化时，都主动更新缓冲区间
          _updateBufferedRanges();
        }
      });
    });

    // 创建一个单独的定时器定期检查和更新加载进度
    Timer.periodic(const Duration(milliseconds: 500), (timer) {
      if (!_disposed) {
        _calculateLoadingProgress();
        // 同时检查是否处于缓冲状态
        final isCurrentlyBuffering =
            _player.processingState == ProcessingState.buffering ||
            _player.processingState == ProcessingState.loading;

        // 只有当缓冲状态发生变化时才更新
        if (_currentState.isBuffering != isCurrentlyBuffering) {
          _updateState(isBuffering: isCurrentlyBuffering);
        }
      } else {
        // 如果已销毁，取消定时器
        timer.cancel();
      }
    });

    _player.playerStateStream.listen((playerState) {
      if (_disposed) return;

      final isBuffering =
          playerState.processingState == ProcessingState.buffering ||
          playerState.processingState == ProcessingState.loading;

      _updateState(
        isBuffering: isBuffering,
        isPlaying: playerState.playing,
        error: null,
      );

      if (playerState.processingState == ProcessingState.completed) {
        _player.seek(Duration.zero);
        _player.pause();
      }
    });

    // 创建定时器定期更新位置 - 降低更新频率
    _positionRefreshTimer = Timer.periodic(const Duration(milliseconds: 1000), (
      timer,
    ) {
      if (!_disposed && _player.playing && !_currentState.isBuffering) {
        _updateCurrentPosition();
        // 同时更新缓冲状态，确保进度条显示正确
        _updateBufferedRanges();
      }
    });

    // 处理播放错误
    _player.playbackEventStream.listen(
      (event) {
        // 监听加载进度但防止过于频繁更新
        if (event.bufferedPosition.inMilliseconds > 0 &&
            _currentState.duration.inMilliseconds > 0) {
          _calculateLoadingProgress();
        }
      },
      onError: (Object e) {
        if (_disposed) return;

        // 检测平台
        bool isAndroid =
            kIsWeb ? false : defaultTargetPlatform == TargetPlatform.android;

        print('音频播放错误: $e');

        // 分析错误类型，提供更有针对性的错误信息
        String errorMessage = AudioErrorHandler.getFriendlyErrorMessage(
          e,
          isAndroid: isAndroid,
        );
        _updateState(error: errorMessage);

        // 判断是否为卡住缓冲的特殊错误
        if (AudioErrorHandler.isStuckBufferingError(e)) {
          print('检测到播放卡住缓冲，执行完全重置');
          _handleStuckBuffering();
        }
        // 判断是否为缓冲区大小问题
        else if (e.toString().contains('Buffer too small')) {
          print('检测到缓冲区大小不足，增大缓冲区');
          _increaseBufferSize(e);
          _tryRecoverFromBufferError();
        }
        // 对Android上的MediaCodec错误采取特殊处理
        else if (isAndroid &&
            (AudioErrorHandler.isMediaCodecError(e) ||
                AudioErrorHandler.isBufferingError(e))) {
          print('检测到Android MediaCodec或缓冲错误，使用特殊恢复流程');
          _tryRecoverAndroidMediaCodec();
        } else {
          // 对其他错误使用普通恢复
          _tryRecover();
        }
      },
    );
  }

  // 添加计算和更新加载进度的专用方法
  void _calculateLoadingProgress() {
    if (_disposed ||
        _currentState.duration.inMilliseconds <= 0 ||
        _player.bufferedPosition.inMilliseconds <= 0)
      return;

    final progress =
        _player.bufferedPosition.inMilliseconds /
        _currentState.duration.inMilliseconds;

    // 只有当进度变化明显时才更新状态 (变化超过1%)
    final currentProgress = _currentState.loadingProgress;
    if ((progress - currentProgress).abs() > 0.01) {
      _updateState(loadingProgress: progress.clamp(0.0, 1.0));
    }
  }

  /// 从错误消息中提取需要的缓冲区大小并增加缓冲区
  void _increaseBufferSize(dynamic error) {
    try {
      final errorMsg = error.toString();
      final regex = RegExp(r'Buffer too small \((\d+) < (\d+)\)');
      final match = regex.firstMatch(errorMsg);

      if (match != null && match.groupCount >= 2) {
        final currentSize = int.parse(match.group(1)!);
        final requiredSize = int.parse(match.group(2)!);

        // 将缓冲区大小设为所需大小的1.5倍，确保足够大
        _bufferSize = (requiredSize * 1.5).toInt();
        print(
          '增大缓冲区大小至: $_bufferSize (原始大小: $currentSize, 需求大小: $requiredSize)',
        );
      } else {
        // 如果无法解析错误，则将缓冲区翻倍
        _bufferSize *= 2;
        print('无法解析错误细节，将缓冲区大小增加到: $_bufferSize');
      }
    } catch (e) {
      print('解析缓冲区错误信息失败: $e');
      // 默认增加缓冲区大小
      _bufferSize = _bufferSize * 2;
    }
  }

  /// 专门处理缓冲区大小问题的恢复方法
  void _tryRecoverFromBufferError() {
    if (_disposed || _recoveryTimer != null) return;

    if (_retryCount >= _maxRetryCount) {
      _updateState(error: '缓冲区错误，尝试恢复失败，请重新加载');
      return;
    }

    _retryCount++;

    // 设置恢复定时器，快速尝试恢复
    _recoveryTimer = Timer(const Duration(milliseconds: 300), () async {
      _recoveryTimer = null;

      if (_disposed) return;

      _updateState(error: '正在修复缓冲区问题 (尝试 $_retryCount/$_maxRetryCount)...');

      try {
        if (_currentUrl != null) {
          final wasPlaying = _currentState.isPlaying;
          final position = _currentState.position;

          // 完全停止播放器
          await _player.stop();

          // 给系统时间释放资源
          await Future.delayed(const Duration(milliseconds: 200));

          // 使用新的缓冲区大小设置
          // 注意：这里无法直接修改just_audio的内部缓冲区大小，
          // 但通过重新加载并使用不同的播放策略可以减轻问题
          await _player.setUrl(_currentUrl!, headers: _currentHeaders);

          // 等待初始化
          await Future.delayed(const Duration(milliseconds: 300));

          // 跳转策略：先跳到安全位置，再慢慢接近目标
          if (position.inSeconds > 10) {
            // 先跳到更安全的位置
            await _player.seek(
              Duration(seconds: math.min(10, position.inSeconds ~/ 4)),
            );
            await Future.delayed(const Duration(milliseconds: 200));

            // 如果位置较远，分段跳转
            if (position.inSeconds > 30) {
              await _player.seek(Duration(seconds: position.inSeconds ~/ 2));
              await Future.delayed(const Duration(milliseconds: 200));
            }
          }

          // 最后跳到目标位置
          await _player.seek(position);

          // 恢复播放状态
          if (wasPlaying) {
            await Future.delayed(const Duration(milliseconds: 100));
            await _player.play();
          }

          _updateState(error: null);
          _retryCount = 0; // 重置重试计数
        }
      } catch (e) {
        print('缓冲区恢复错误: $e');
        _updateState(error: '缓冲区问题，再次尝试修复...');
        _tryRecoverFromBufferError(); // 继续尝试恢复
      }
    });
  }

  /// 更新当前位置
  Future<void> _updateCurrentPosition() async {
    try {
      final position = await _player.position;
      _updateState(position: position);
    } catch (e) {
      // 忽略错误
    }
  }

  /// 更新缓冲区间
  void _updateBufferedRanges() {
    if (_disposed) return;

    final duration = _currentState.duration;
    final bufferedPosition = _currentState.bufferedPosition;

    if (duration.inMilliseconds <= 0 || bufferedPosition.inMilliseconds <= 0)
      return;

    // 始终创建一个从起始位置到当前缓冲位置的区间
    final newRange = BufferedRange(Duration.zero, bufferedPosition);

    // 检查缓冲区间是否有重大变化（超过500毫秒）
    bool hasSignificantChange = true;
    if (_bufferedRanges.isNotEmpty) {
      final lastRange = _bufferedRanges.last;
      final diff =
          (bufferedPosition.inMilliseconds - lastRange.end.inMilliseconds)
              .abs();
      hasSignificantChange = diff > 500;
    }

    // 只有在有明显变化时才更新UI
    if (hasSignificantChange) {
      _bufferedRanges.clear();
      _bufferedRanges.add(newRange);

      // 更新状态
      _updateState(
        bufferedRanges: List.from(_bufferedRanges),
        loadingProgress:
            bufferedPosition.inMilliseconds / duration.inMilliseconds,
      );
    }
  }

  /// 更新状态
  void _updateState({
    Duration? position,
    Duration? bufferedPosition,
    Duration? duration,
    bool? isPlaying,
    bool? isLoading,
    bool? isBuffering,
    String? error,
    List<BufferedRange>? bufferedRanges,
    double? loadingProgress,
    String? currentUrl,
  }) {
    // 防止在disposed后更新状态
    if (_disposed) return;

    // 使用微任务确保状态更新是同步的
    Future.microtask(() {
      _currentState = _currentState.copyWith(
        position: position,
        bufferedPosition: bufferedPosition,
        duration: duration,
        isPlaying: isPlaying,
        isLoading: isLoading,
        isBuffering: isBuffering,
        error: error,
        bufferedRanges: bufferedRanges,
        loadingProgress: loadingProgress,
        currentUrl: currentUrl ?? _currentUrl, // 更新当前URL
      );

      if (!_disposed && !_stateController.isClosed) {
        _stateController.add(_currentState);
      }
    });
  }

  /// 加载URL
  Future<void> loadUrl(
    String url, {
    Map<String, String>? headers,
    bool autoPlay = false,
  }) async {
    if (_disposed) return;

    // 重要：当加载新的URL时，总是重置播放器状态
    if (_currentUrl != url) {
      _bufferedRanges.clear();
      _loadingProgress = 0.0;
      _failedToLoad = false;
      _retryCount = 0;

      // 确保完全停止当前播放
      try {
        await _player.stop();
        // 给系统一些时间释放资源
        await Future.delayed(const Duration(milliseconds: 300));
      } catch (e) {
        print('停止播放器时出错: $e');
        // 继续执行，不因此中断加载
      }

      _updateState(
        position: Duration.zero,
        bufferedPosition: Duration.zero,
        duration: Duration.zero,
        isPlaying: false,
        isLoading: true,
        isBuffering: false,
        error: null,
        loadingProgress: 0.0,
      );
    }

    try {
      _updateState(isLoading: true, error: null);
      _currentUrl = url;
      _currentHeaders = headers;
      _failedToLoad = false;
      _retryCount = 0;

      // 如果播放器处于idle状态或者URL变化，重新设置URL
      if (_player.processingState == ProcessingState.idle ||
          _currentUrl != url) {
        await _player.stop(); // 确保先停止
        await Future.delayed(const Duration(milliseconds: 100));

        // 重置播放器设置，以确保不会使用上一个音频的配置
        await _player.setUrl(url, headers: headers);
        await Future.delayed(const Duration(milliseconds: 300));
      }

      final duration = _player.duration ?? Duration.zero;

      _updateState(
        duration: duration,
        isLoading: false,
        position: Duration.zero,
        bufferedPosition: Duration.zero,
        loadingProgress: 0.0,
        currentUrl: url, // 更新URL信息
      );

      if (autoPlay) {
        await Future.delayed(const Duration(milliseconds: 200));
        await play();
      }

      if (_seekTarget != null) {
        await Future.delayed(const Duration(milliseconds: 200));
        await seek(_seekTarget!);
        _seekTarget = null;
      }
    } catch (e) {
      _failedToLoad = true;
      _updateState(isLoading: false, error: '加载音频失败: $e');
      _tryRecover();
    }
  }

  /// 播放
  Future<void> play() async {
    if (_disposed) return;

    try {
      // 清除之前的错误状态
      _updateState(error: null);

      // 如果当前没有URL，直接返回
      if (_currentUrl == null) {
        return;
      }

      // 如果之前加载失败，重新加载前先重置状态
      if (_failedToLoad) {
        _failedToLoad = false;
        _retryCount = 0;
        await _player.stop();
        await Future.delayed(const Duration(milliseconds: 100));
        await loadUrl(_currentUrl!, headers: _currentHeaders);
      }

      // 确保不在缓冲状态
      if (!_currentState.isBuffering) {
        await _player.play();
      } else {
        // 如果正在缓冲，等待一小段时间后重试
        await Future.delayed(const Duration(milliseconds: 500));
        if (!_disposed && !_currentState.isBuffering) {
          await _player.play();
        }
      }
    } catch (e) {
      print('播放错误: $e');
      // 避免重复显示错误
      if (!_currentState.hasError) {
        _updateState(error: '播放错误: $e');
        // 只有在非致命错误时才尝试恢复
        if (!AudioErrorHandler.isMediaCodecError(e)) {
          _tryRecover();
        }
      }
    }
  }

  /// 暂停
  Future<void> pause() async {
    if (_disposed) return;

    try {
      await _player.pause();
    } catch (e) {
      print('暂停错误: $e');
    }
  }

  /// 跳转到指定位置
  Future<void> seek(Duration position) async {
    if (_disposed) return;

    try {
      // 如果播放器尚未准备好，保存跳转目标
      if (_currentState.isLoading || _failedToLoad) {
        _seekTarget = position;
        print('播放器未准备好，保存跳转目标: $position');
        return;
      }

      // 确保位置有效
      final validPosition = _validatePosition(position);

      // 检测平台 - Android平台需要特殊处理
      bool isAndroid =
          kIsWeb ? false : defaultTargetPlatform == TargetPlatform.android;

      // 先检查是否是跳转到已缓冲区域
      final isBuffered = _currentState.isPositionBuffered(validPosition);
      print('跳转到位置 $validPosition, 是否已缓冲: $isBuffered');

      // 记录播放状态，以便恢复
      final wasPlaying = _currentState.isPlaying;

      // 如果跳转到已缓冲区域，可以直接跳转
      if (isBuffered) {
        print('跳转到已缓冲区域，直接跳转');

        // 即便是缓冲区域，Android平台也建议先暂停再跳转以提高稳定性
        if (isAndroid && wasPlaying) {
          await _player.pause();
          await Future.delayed(const Duration(milliseconds: 50));
          await _player.seek(validPosition);

          // 快速恢复播放
          if (wasPlaying) {
            await Future.delayed(const Duration(milliseconds: 50));
            await _player.play();
          }
        } else {
          // 非Android平台或已暂停状态，可以直接跳转
          await _player.seek(validPosition);

          // 如果之前在播放，确保继续播放
          if (wasPlaying && !_player.playing) {
            await _player.play();
          }
        }

        _updateState(position: validPosition);
        return;
      }

      // 以下是未缓冲区域的处理逻辑，需要更谨慎的跳转策略

      // 始终暂停后再跳转，特别是在Android平台上，大大减少错误概率
      if (wasPlaying) {
        await _player.pause();
        // 给系统足够时间处理暂停
        await Future.delayed(const Duration(milliseconds: 200));
      }

      // 检查播放器状态，如果是缓冲状态，需要特殊处理
      if (_currentState.isBuffering) {
        print('跳转时播放器处于缓冲状态，使用更安全的跳转策略');
        // 先停止播放器
        await _player.stop();
        await Future.delayed(const Duration(milliseconds: 300));

        // 重新加载URL
        if (_currentUrl != null) {
          await _player.setUrl(_currentUrl!, headers: _currentHeaders);
          await Future.delayed(const Duration(milliseconds: 300));

          // 使用分段跳转
          await _player.seek(validPosition);
          if (wasPlaying) {
            await Future.delayed(const Duration(milliseconds: 100));
            await _player.play();
          }
        }
        return;
      }

      // 智能跳转 - 检查请求的位置是否已缓冲
      if (_isSmartSeekEnabled && _currentState.bufferedRanges.isNotEmpty) {
        // 此处的isBuffered检查应该已经被前面的判断覆盖，但为了保持逻辑完整性，继续执行
        if (!isBuffered) {
          print('跳转位置未缓冲: $validPosition, 使用智能跳转');

          // 如果请求位置未缓冲，先找到最近的缓冲点
          final nearestBuffered = _currentState.getNearestBufferedPosition(
            validPosition,
          );
          print('最近的缓冲点: $nearestBuffered');

          // 更新缓冲状态
          _updateState(isBuffering: true, error: null);

          try {
            // Android平台使用更安全的跳转策略
            if (isAndroid) {
              print('Android平台: 使用更安全的跳转策略');

              // 先跳到最安全的位置（起始位置）
              await _player.seek(Duration.zero);
              await Future.delayed(const Duration(milliseconds: 200));

              // 分段跳转策略
              if (validPosition.inSeconds > 30) {
                // 第一段跳转 - 跳到目标位置的1/4处
                final firstStep = Duration(
                  seconds: validPosition.inSeconds ~/ 4,
                );
                await _player.seek(firstStep);
                await Future.delayed(const Duration(milliseconds: 200));

                // 第二段跳转 - 跳到目标位置的1/2处
                final secondStep = Duration(
                  seconds: validPosition.inSeconds ~/ 2,
                );
                await _player.seek(secondStep);
                await Future.delayed(const Duration(milliseconds: 200));
              }

              // 最后跳到目标位置
              await _player.seek(validPosition);
            } else {
              // 非Android平台的两段跳转策略
              // 先跳到已缓冲位置
              await _player.seek(nearestBuffered);
              await Future.delayed(const Duration(milliseconds: 300));

              // 再跳到目标位置
              await _player.seek(validPosition);
            }

            // 恢复播放状态
            if (wasPlaying) {
              await Future.delayed(const Duration(milliseconds: 200));
              await _player.play();
            }
          } catch (e) {
            print('智能跳转出错: $e，尝试安全跳转');

            // 如果智能跳转失败，尝试更安全的方式
            try {
              // 先完全停止播放器
              await _player.stop();
              await Future.delayed(const Duration(milliseconds: 200));

              // 重新加载URL
              if (_currentUrl != null) {
                await _player.setUrl(_currentUrl!, headers: _currentHeaders);
                await Future.delayed(const Duration(milliseconds: 300));

                // 分段跳转到目标位置
                if (validPosition.inSeconds > 10) {
                  // 先跳到一个安全位置
                  await _player.seek(
                    Duration(
                      seconds: math.min(10, validPosition.inSeconds ~/ 5),
                    ),
                  );
                  await Future.delayed(const Duration(milliseconds: 200));
                }

                // 最终跳转
                await _player.seek(validPosition);

                // 恢复播放状态
                if (wasPlaying) {
                  await Future.delayed(const Duration(milliseconds: 200));
                  await _player.play();
                }
              }
            } catch (e2) {
              print('安全跳转也失败: $e2');
              _updateState(error: '跳转失败，请重试');
            }
          }
        } else {
          // 位置已缓冲，直接跳转 - 这部分逻辑应该已被前面的判断处理，但保留以确保兼容性
          print('位置已缓冲，直接跳转: $validPosition');
          await _player.seek(validPosition);

          // 恢复播放状态
          if (wasPlaying) {
            await Future.delayed(const Duration(milliseconds: 100));
            await _player.play();
          }
        }
      } else {
        // 不使用智能跳转，直接跳转
        print('不使用智能跳转，直接跳转: $validPosition');
        await _player.seek(validPosition);

        // 恢复播放状态
        if (wasPlaying) {
          await Future.delayed(const Duration(milliseconds: 100));
          await _player.play();
        }
      }

      _updateState(position: validPosition);
    } catch (e) {
      print('跳转错误: $e');
      _updateState(error: '跳转错误: $e');
    }
  }

  /// 验证位置在有效范围内
  Duration _validatePosition(Duration position) {
    final duration = _currentState.duration;

    if (duration.inMilliseconds <= 0) {
      return Duration.zero;
    }

    if (position < Duration.zero) {
      return Duration.zero;
    }

    if (position > duration) {
      return duration;
    }

    return position;
  }

  /// 尝试恢复播放
  void _tryRecover() {
    if (_disposed || _recoveryTimer != null) return;

    if (_retryCount >= _maxRetryCount) {
      _updateState(error: '尝试恢复播放失败，请重新加载');
      return;
    }

    _retryCount++;

    // 创建恢复定时器
    _recoveryTimer = Timer(const Duration(seconds: 2), () async {
      _recoveryTimer = null;

      if (_disposed) return;

      _updateState(error: '正在尝试恢复播放 (尝试 $_retryCount/$_maxRetryCount)...');

      try {
        if (_currentUrl != null) {
          final wasPlaying = _currentState.isPlaying;
          final position = _currentState.position;

          // 重新加载URL
          await _player.stop();
          await Future.delayed(const Duration(milliseconds: 200));
          await _player.setUrl(_currentUrl!, headers: _currentHeaders);

          // 恢复位置
          if (position.inMilliseconds > 0) {
            await Future.delayed(const Duration(milliseconds: 200));
            await _player.seek(position);
          }

          // 如果之前在播放，恢复播放
          if (wasPlaying) {
            await Future.delayed(const Duration(milliseconds: 100));
            await _player.play();
          }

          _updateState(error: null);
          _needReloadUrl = false;
        }
      } catch (e) {
        print('恢复播放错误: $e');
        _needReloadUrl = true;
        _updateState(error: '恢复播放失败: $e');

        // 继续尝试恢复
        _tryRecover();
      }
    });
  }

  /// 专门用于Android MediaCodec错误的恢复方法
  void _tryRecoverAndroidMediaCodec() {
    if (_disposed || _recoveryTimer != null) return;

    // 对MediaCodec错误，重置计数，因为这类错误通常需要更多次重试
    if (_retryCount >= 5) {
      _updateState(error: 'Android解码器错误，无法自动恢复，请重新加载');
      return;
    }

    _retryCount++;

    // 用更短的延迟，立即尝试恢复
    _recoveryTimer = Timer(const Duration(milliseconds: 500), () async {
      _recoveryTimer = null;

      if (_disposed) return;

      _updateState(error: '正在修复播放器 (尝试 $_retryCount/5)...');

      try {
        // 保存当前播放位置和状态
        final wasPlaying = _currentState.isPlaying;
        final position = _currentState.position;

        // 完全重置播放器
        await _player.stop();

        // 等待系统资源释放
        await Future.delayed(const Duration(milliseconds: 300));

        if (_currentUrl != null) {
          // 重新加载URL，从头开始流式加载
          await _player.setUrl(_currentUrl!, headers: _currentHeaders);

          // 等待初始化
          await Future.delayed(const Duration(milliseconds: 300));

          // 先尝试接近起始位置的跳转，避免直接跳到问题区域
          if (position.inSeconds > 30) {
            // 使用分段跳转策略，防止一次跳转太远
            final firstStep = Duration(seconds: 10);
            await _player.seek(firstStep);
            await Future.delayed(const Duration(milliseconds: 200));

            final secondStep = Duration(seconds: position.inSeconds ~/ 3);
            await _player.seek(secondStep);
            await Future.delayed(const Duration(milliseconds: 200));

            final thirdStep = Duration(seconds: position.inSeconds * 2 ~/ 3);
            await _player.seek(thirdStep);
            await Future.delayed(const Duration(milliseconds: 200));
          }

          // 再恢复到原来的位置
          await _player.seek(position);

          // 如果之前在播放，恢复播放
          if (wasPlaying) {
            await Future.delayed(const Duration(milliseconds: 200));
            await _player.play();
          }

          _updateState(error: null);
          _needReloadUrl = false;
          _retryCount = 0; // 重置重试计数
        }
      } catch (e) {
        print('Android解码器恢复失败: $e');

        // 恢复失败，继续尝试恢复
        _updateState(error: 'Android解码器错误，再次尝试修复...');
        _tryRecoverAndroidMediaCodec();
      }
    });
  }

  /// 设置智能跳转
  void setSmartSeek(bool enabled) {
    _isSmartSeekEnabled = enabled;
  }

  /// 设置最大重试次数
  void setMaxRetryCount(int count) {
    _maxRetryCount = count;
  }

  /// 释放资源
  void dispose() {
    if (_disposed) return;

    _disposed = true;

    try {
      _positionRefreshTimer?.cancel();
      _recoveryTimer?.cancel();

      // 确保先暂停播放
      try {
        _player.pause();
      } catch (e) {
        // 忽略暂停错误
      }

      Future.delayed(const Duration(milliseconds: 100), () {
        try {
          _player.dispose();
        } catch (e) {
          print('安全销毁播放器时出错: $e');
        }
      });
    } catch (e) {
      print('播放器销毁时出错: $e');
    } finally {
      try {
        if (!_stateController.isClosed) {
          _stateController.close();
        }
      } catch (e) {
        // 忽略关闭流错误
      }
    }
  }

  /// 专门处理播放卡住缓冲不加载的问题
  void _handleStuckBuffering() {
    if (_disposed || _recoveryTimer != null) return;

    _retryCount++;
    if (_retryCount > 5) {
      _updateState(error: '缓冲卡住问题无法恢复，请重新加载');
      return;
    }

    // 立即启动恢复流程，不等待
    _recoveryTimer = Timer(const Duration(milliseconds: 100), () async {
      _recoveryTimer = null;

      if (_disposed) return;

      _updateState(error: '正在重置播放器 (尝试 $_retryCount/5)...');

      try {
        if (_currentUrl != null) {
          // 保存当前状态
          final wasPlaying = _currentState.isPlaying;
          final position = _currentState.position;

          // 完全停止并释放播放器资源
          await _player.stop();

          // 确保给系统足够时间释放资源
          await Future.delayed(const Duration(milliseconds: 500));

          // 重新初始化播放器 - 完全重置状态
          await _player.setUrl(_currentUrl!, headers: _currentHeaders);

          // 等待初始化完成
          await Future.delayed(const Duration(milliseconds: 500));

          // 使用更安全的跳转方式恢复位置
          if (position.inSeconds > 0) {
            // 先跳到更安全的位置（例如文件开始）
            await _player.seek(Duration.zero);
            await Future.delayed(const Duration(milliseconds: 200));

            // 使用分段跳转策略避免直接跳到问题区域
            if (position.inSeconds > 30) {
              // 先跳转到1/4位置
              await _player.seek(Duration(seconds: position.inSeconds ~/ 4));
              await Future.delayed(const Duration(milliseconds: 200));

              // 再跳转到一半位置
              await _player.seek(Duration(seconds: position.inSeconds ~/ 2));
              await Future.delayed(const Duration(milliseconds: 200));
            }

            // 最后尝试跳转到目标位置
            await _player.seek(position);
            await Future.delayed(const Duration(milliseconds: 200));
          }

          // 恢复播放状态
          if (wasPlaying) {
            await _player.play();
          }

          _updateState(error: null, isBuffering: false);
          _retryCount = 0; // 重置计数
        }
      } catch (e) {
        print('处理缓冲卡住错误失败: $e');
        _updateState(error: '缓冲问题仍然存在，再次尝试中...');

        // 继续尝试恢复
        _handleStuckBuffering();
      }
    });
  }
}

/// 音频播放器提供者 - 使用多实例模式，每个URL创建独立实例
final audioPlayerProvider =
    StateNotifierProvider<AudioPlayerNotifier, AudioPlayerState>((ref) {
      // 确保在程序退出/组件树销毁时释放资源
      ref.onDispose(() {
        print('audioPlayerProvider被销毁，确保释放所有资源');
      });
      return AudioPlayerNotifier();
    });

class AudioPlayerNotifier extends StateNotifier<AudioPlayerState> {
  final EnhancedAudioPlayer _player = EnhancedAudioPlayer();
  bool _isReleasing = false;
  bool _isInitializing = false; // 添加初始化锁
  bool _isDisposed = false; // 跟踪是否已经销毁

  AudioPlayerNotifier() : super(const AudioPlayerState()) {
    _subscribeToStateChanges();
  }

  @override
  void dispose() {
    if (_isDisposed) return;

    _isDisposed = true;
    try {
      _player.dispose();
    } catch (e) {
      print('安全销毁播放器时出错: $e');
      // 忽略错误，继续销毁过程
    }
    super.dispose();
  }

  /// 安全暂停播放
  Future<void> safetyPause() async {
    if (_isDisposed) return;

    try {
      await _player.pause();
    } catch (e) {
      print('安全暂停播放器时出错: $e');
      // 忽略错误
    }
  }

  /// 释放资源并完全重置状态
  Future<void> release() async {
    if (_isReleasing || _isDisposed) return;

    _isReleasing = true;
    try {
      await _player.pause();
      _unsubscribeFromStateChanges(); // 取消订阅
      state = const AudioPlayerState(); // 重置状态
      _subscribeToStateChanges(); // 重新订阅状态
    } catch (e) {
      print('释放播放器资源时出错: $e');
      // 发生错误时重置状态
      state = const AudioPlayerState();
    } finally {
      _isReleasing = false;
    }
  }

  /// 加载URL
  Future<void> loadUrl(
    String url, {
    Map<String, String>? headers,
    bool autoPlay = false,
  }) async {
    if (_isReleasing || _isInitializing) return;
    _isInitializing = true;
    try {
      // 如果URL改变，先完全释放当前播放器资源
      if (state.currentUrl != null && state.currentUrl != url) {
        await release();
        await Future.delayed(const Duration(milliseconds: 100));
      }

      await _player.loadUrl(url, headers: headers, autoPlay: autoPlay);
    } finally {
      _isInitializing = false;
    }
  }

  /// 播放
  Future<void> play() async {
    await _player.play();
  }

  /// 暂停
  Future<void> pause() async {
    await _player.pause();
  }

  /// 跳转
  Future<void> seek(Duration position) async {
    await _player.seek(position);
  }

  /// 设置智能跳转
  void setSmartSeek(bool enabled) {
    _player.setSmartSeek(enabled);
  }

  /// 设置最大重试次数
  void setMaxRetryCount(int count) {
    _player.setMaxRetryCount(count);
  }

  /// 订阅状态变更
  void _subscribeToStateChanges() {
    _player.stateStream.listen((newState) {
      state = newState;
    });
  }

  /// 取消订阅状态变更
  void _unsubscribeFromStateChanges() {
    state = const AudioPlayerState();
  }

  /// 安全跳转方法，特别适用于FLAC和大文件
  Future<void> safeSeek(Duration position) async {
    try {
      // 记录当前状态
      final currentState = state;
      final wasPlaying = currentState.isPlaying;

      // 如果正在播放，先暂停
      if (wasPlaying) {
        await _player.pause();
      }

      // 更新状态为缓冲中
      state = state.copyWith(isBuffering: true);

      // 使用更低级别的API进行跳转，避免ExoPlayer的自动缓冲逻辑
      await _player.seek(position);

      // 给予足够的时间让播放器处理跳转
      await Future.delayed(const Duration(milliseconds: 300));

      // 更新状态 - 使用传入的位置作为当前位置
      state = state.copyWith(position: position, isBuffering: false);

      // 如果之前是播放状态，恢复播放
      if (wasPlaying) {
        // 再次延迟以确保缓冲完成
        await Future.delayed(const Duration(milliseconds: 200));
        await _player.play();
      }
    } catch (e) {
      print('安全跳转出错: $e');
      // 尝试常规跳转作为备选
      await seek(position);
    }
  }
}
